package com.ruoyi.project.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ZeWu;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.domain.dto.TwoEleResult;
import com.ruoyi.project.system.domain.vo.SiyuQueryVo;
import com.ruoyi.project.system.mapper.*;
import com.ruoyi.project.system.service.ISiyuQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 进件记录Service业务层处理
 */
@Service
public class SiyuQueryServiceImpl implements ISiyuQueryService {

    @Autowired
    private SiyuQueryMapper siyuQueryMapper;

    @Autowired
    private SiyuUserPriceMapper siyuUserPriceMapper;

    @Autowired
    private SiyuProductMapper siyuProductMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SiyuChargeMapper siyuChargeMapper;

    @Autowired
    private SiyuBaseinfoMapper siyuBaseinfoMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private RedisCache rc;

    @Value("${back_url}")
    private String back_url;

    @Value("${notify_url}")
    private String notify_url;

    @Value("${license_url}")
    private String license_url;

    @Override
    @Transactional
    public int extracted(String data, Integer ID) {
        SiyuBaseinfo baseInfo = siyuBaseinfoMapper.baseInfo(ID.longValue());
        if (baseInfo == null) {
            SiyuBaseinfo info = new SiyuBaseinfo(data);
            // 写入查询结果
            siyuBaseinfoMapper.insertSiyuBaseinfo(info);
            // 写入记录编号
            return siyuQueryMapper.updateSiyuQuery(new SiyuQuery(ID, info.getId().intValue()));
        } else {
            baseInfo.setBaseInfo(data);
            return siyuBaseinfoMapper.updateSiyuBaseinfo(baseInfo);
        }
    }

    @Override
    @Transactional
    public SiyuQuery selectData(String apiNo, SiyuQuery siyuQuery) {
        SiyuProduct product = siyuProductMapper.selectSiyuProductById(siyuQuery.getId());
        // 扣费
        fee(siyuQuery, product.getName());
        // 写入查询结果
        SiyuQuery query;
        if (siyuQuery.getId() < 16) {
            String key = "TEM::" + siyuQuery.getCardNo() + "::" + product.getCode();
            String result = rc.getCacheObject(key);
            if (StringUtils.isEmpty(result)) {
                if ("ZCI102".equals(product.getCode())) {
                    this.makeAccredit(siyuQuery);
                }
                result = ZeWu.getResult(product.getCode(), siyuQuery);

                JSONObject js = JSON.parseObject(result);
                if ("200".equals(js.getString("code"))) {
                    rc.setCacheObject("TEM::" + siyuQuery.getCardNo() + "::" + product.getCode(), result, 1, TimeUnit.HOURS);
                }
            }
            query = new SiyuQuery(siyuQuery, result);
            siyuQueryMapper.updateSiyuQuery(query);
        } else if (siyuQuery.getId() == 18) {
            String result = "https://flow-process.eeiai.cn/billProcess?accountId=50c639f80d34442c80b53ac59857692d";
            try {
                result += "&backUrl=" + URLEncoder.encode(back_url, "UTF-8");
                result += "&idCard=" + siyuQuery.getCardNo() + "&userName=" + siyuQuery.getName();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            query = new SiyuQuery(result);
            siyuQueryMapper.insertQueryInfo(siyuQuery.getQueryId(), siyuQuery.getId(), apiNo, result);
        } else {
            query = new SiyuQuery();
//            siyuQueryMapper.insertQueryInfo(siyuQuery.getQueryId(), siyuQuery.getId(), apiNo, "OK");
        }
        sysConfigMapper.addInterNum();
        return query;
    }

    @Async
    public void makeAccredit(SiyuQuery siyuQuery) {
        try {
            // 读取 PDF 模板文件
            PdfReader reader = new PdfReader(RuoYiConfig.getProfile() + "/授权书.pdf");
            // 创建一个输出流，用于保存新生成的 PDF
            FileOutputStream outputStream = new FileOutputStream(RuoYiConfig.getProfile() + "/SQS" + siyuQuery.getQueryId() + ".pdf");
            // 创建一个 PdfStamper 对象，用于操作 PDF 内容
            PdfStamper stamper = new PdfStamper(reader, outputStream);

            // 获取 PDF 表单
            AcroFields form = stamper.getAcroFields();
            // 设置支持中文
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(baseFont);

            // 准备要替换的数据
            Map<String, String> data = new HashMap<>();
            data.put("name", siyuQuery.getName());
            data.put("cardNo", siyuQuery.getCardNo());
            data.put("date", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")));
            // 替换表单中的占位符
            for (Map.Entry<String, String> entry : data.entrySet()) {
                String fieldName = entry.getKey();
                String fieldValue = entry.getValue();
                form.setField(fieldName, fieldValue);
            }
            // 关闭表单编辑
            stamper.setFormFlattening(true);
            // 关闭 stamper 和 reader
            stamper.close();
            reader.close();
            outputStream.close();

            System.out.println("新的 PDF 文档生成成功！");
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
            System.out.println("生成新的 PDF 文档失败：" + e.getMessage());
        }
    }


    public void baseFee(SiyuQuery siyuQuery, String productName) {
        List<SiyuCharge> charges = siyuChargeMapper.selectSiyuChargeList(new SiyuCharge(
                siyuQuery.getUserId().intValue(),
                siyuQuery.getQueryId(),
                productName,
                siyuQuery.getAuthCode()
        ));
        if (charges == null || charges.isEmpty()) {
            fee(siyuQuery, productName);
        }
    }

    public void fee(SiyuQuery siyuQuery, String productName) {
        Long userId;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            userId = siyuQuery.getUserId().longValue();
        }
        BigDecimal balance = sysUserMapper.selectUserById(userId.longValue()).getBalance();
        BigDecimal price;
        SiyuUserPrice siyuUserPrice = siyuUserPriceMapper.selectPriceByUIAadPI(userId.toString(), siyuQuery.getId().toString());
        if (siyuUserPrice != null) {
            price = siyuUserPrice.getPrice();
        } else {
            price = siyuProductMapper.selectSiyuProductById(siyuQuery.getId().intValue()).getUnitPrice();
        }
        // 写入扣费记录
        siyuChargeMapper.insertSiyuCharge(new SiyuCharge(
                userId.intValue(),
                siyuQuery.getQueryId(),
                balance,
                price,
                balance.subtract(price),
                productName,
                siyuQuery.getAuthCode()
        ));
        // 减余额
        sysUserMapper.subtractBalance(userId.longValue(), price);
    }

    @Override
    public TwoEleResult verificationTwoEle(SiyuQuery siyuQuery) {
        // MGZ TODO 2025/6/4: 进件二要素核查
        JSONObject params = new JSONObject();
        params.put("req_time", System.currentTimeMillis());
        params.put("request_sn", "YQ" + IdUtils.fastSimpleUUID().substring(0, 13).toUpperCase() + "JF061");
        params.put("inter_id", "JF061");
        params.put("name", siyuQuery.getName());
        params.put("cardNo", siyuQuery.getCardNo());
        try {
            JSONObject smrz_ = JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params));
            if ("000000".equals(smrz_.getString("retcode"))) {
                if (smrz_.getJSONObject("retdata").getInteger("status") == 1) {
                    return new TwoEleResult();
                } else if (smrz_.getJSONObject("retdata").getInteger("status") == 2) {
                    return new TwoEleResult("姓名，身份证核验不一致");
                }
            }
            params.replace("request_sn", "YQ" + IdUtils.fastSimpleUUID().substring(0, 13).toUpperCase() + "JF005");
            params.replace("inter_id", "JF005");
            JSONObject smrz = JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params));
            if ("000000".equals(smrz.getString("retcode")) && "0".equals(smrz.getJSONObject("retdata").getString("final_valid_result"))) {
                return new TwoEleResult();
            } else {
                return new TwoEleResult(smrz.getString("retmsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new TwoEleResult("二要素检验异常");
        }
    }

    public void sysFee() {
        Long userId = SecurityUtils.getUserId();
        BigDecimal balance = sysUserMapper.selectUserById(userId.longValue()).getBalance();
        // 写入扣费记录
        BigDecimal price = new BigDecimal(0.2);
        siyuChargeMapper.insertSiyuCharge(new SiyuCharge(
                userId.intValue(),
                balance,
                price,
                balance.subtract(price),
                "进件二要素核查"
        ));
        // 减余额
        sysUserMapper.subtractBalance(userId.longValue(), price);
    }


    /**
     * 查询进件记录
     *
     * @param queryId 进件记录主键
     * @return 进件记录
     */
    @Override
    public SiyuQuery selectSiyuQueryByQueryId(Integer queryId) {
        return siyuQueryMapper.selectSiyuQueryByQueryId(queryId);
    }

    /**
     * 查询进件记录列表
     *
     * @param siyuQuery 进件记录
     * @return 进件记录
     */
    @Override
    public List<SiyuQueryVo> selectSiyuQueryList(SiyuQuery siyuQuery) {
        return siyuQueryMapper.selectSiyuQueryList(siyuQuery);
    }

    /**
     * 新增进件记录
     *
     * @param siyuQuery 进件记录
     * @return 结果
     */
    @Override
    public int insertSiyuQuery(SiyuQuery siyuQuery) {
        return siyuQueryMapper.insertSiyuQuery(siyuQuery);
    }

    /**
     * 修改进件记录
     *
     * @param siyuQuery 进件记录
     * @return 结果
     */
    @Override
    public int updateSiyuQuery(SiyuQuery siyuQuery) {
        return siyuQueryMapper.updateSiyuQuery(siyuQuery);
    }

    @Override
    public int removeInviteList(Integer[] queryIds) {
        return siyuQueryMapper.removeInviteList(queryIds);
    }

    /**
     * 批量删除进件记录
     *
     * @param queryIds 需要删除的进件记录主键
     * @return 结果
     */
    @Override
    public int deleteSiyuQueryByQueryIds(Integer[] queryIds) {
        siyuQueryMapper.deleteCommByQueryIds(queryIds);
        return siyuQueryMapper.deleteSiyuQueryByQueryIds(queryIds);
    }

}
